﻿namespace EmbeddedSharp.Core
{
    public class DefaultExpressionTranslator : IExpressionTranslator
    {
        #region IExpressionTranslator Members

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public string Translate(Node node)
        {
            string expr = InternalCompile(node);

            //if (expr.StartsWith("(") && expr.EndsWith(")")) {
            //    expr = expr.Remove(0, 1);
            //    expr = expr.Remove(expr.Length - 1, 1);
            //}

            return expr;
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected string InternalCompile(Node node)
        {
            string b = string.Empty;
            if (node is OperatorNode)
            {
                var fn = (OperatorNode) node;
                b = "(";
                b += Translate(fn.Left);
                b += fn.Value;
                b += Translate(fn.Right);
                b += ")";
            }
            else if (node is FuncNode)
            {
                var fn = (FuncNode) node;
                b += fn.Value + "(";
                for (int index = fn.Parameters.Count - 1; index >= 0; index--)
                {
                    b += Translate(fn.Parameters[index]);
                    if (index > 0)
                    {
                        b += ",";
                    }
                }
                b += ")";
            }
            else
            {
                b = ProcessTerminalNode(node);
            }

            return b;
        }

        protected virtual string ProcessTerminalNode(Node node)
        {
            return node.Value;
        }
    }
}